<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * CodeIgniter Application Controller Class
 *
 * This class object is the super class that every library in
 * CodeIgniter will be assigned to.
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/general/controllers.html
 */
class CI_Controller {

	private static $instance;

	protected $currentLoggedClient = '';


	/**
	 * Constructor
	 */
	public function __construct()
	{
		self::$instance =& $this;

		// Assign all the class objects that were instantiated by the
		// bootstrap file (CodeIgniter.php) to local class variables
		// so that CI can run as one big super object.
		foreach (is_loaded() as $var => $class)
		{
			$this->$var =& load_class($class);
		}

		$this->load =& load_class('Loader', 'core');

		$this->load->initialize();

		$this->load->library('session');

		$this->load->helper('file');


		$this->load->helper('download');

		$this->load->helper(array('form', 'url'));

		$this->load->library('form_validation');

		$this->load->library('email');

		$this->load->library('pagination');

		/*if(isset($this->session->userdata('client_id')){
			$this->currentClient = $this->db->query("select * from users where id = ".$this->session->userdata('client_id'));
			}*/

		log_message('debug', "Controller Class Initialized");
	}

	public static function &get_instance()
	{
		return self::$instance;
	}


	public function loadAdminPage($page,$data){
		//$this->loadPage('admin',$page,$data);


		if($this->session->userdata('user_id') == null ){
			return $this->adminLogin($data);

		}
		/*
			$dataq = file_get_contents("./uploadedFiles/txt/me.txt"); // Read the file's contents
			$name = 'myphoto.txt';

			force_download($name, $dataq);
			*/

		$usertype  = $this->session->userdata('user_type');


		$data['allowed'] = false;
		//echo 'nnnnnnnnnnnnnnnnnnnn'.$usertype;
		if($usertype == 'A')
		$data['allowed'] = true;
			
		$folder = 'admin';
			$this->load->view($folder.'/pages/includes/header1', $data);
			$this->load->view($folder.'/pages/'.$page, $data);
			$this->load->view($folder.'/pages/includes/footer1', $data);

	}



	public function adminLogin($data){
		$folder = 'admin';
		$page = 'admin';
		$data['page'] = "login";
		$data['allowed'] = false;
		$this->load->view($folder.'/pages/includes/header1', $data);
		$this->load->view($folder.'/pages/'.$page, $data);
		$this->load->view($folder.'/pages/includes/footer1', $data);

	}

	public function loadClientPage($page,$data){

		$this->loadPage('skybest',$page,$data);
	}


	public function loadPage($folder,$page,$data){


		if ( ! file_exists('_application/views/'.$folder.'/pages/'.$page.'.php'))
		{
			// Whoops, we don't have a page for that!
			if($data['pageExists'])
			$page = "default";
			else
			show_404();
		}
			
			
		//echo "----------------------".file_exists('_application/views/'.$folder.'/pages/'.$page.'.php');
		//echo "222----------------------".file_exists('_application/views/files/ok.txt');
		/*
		$filedata = file_get_contents('_application/views/'.$folder.'/pages/'.'SAAA.txt'); // Read the file's contents
		$name = 'yohan.txt';
		*/
		//	    force_download($name, $filedata);
		if($page == 'printTransactionDetails'){
			$this->load->view($folder.'/pages/'.$page, $data);
		}
		else{
			$this->load->view($folder.'/pages/includes/header', $data);
			$this->load->view($folder.'/pages/'.$page, $data);
			$this->load->view($folder.'/pages/includes/footer', $data);
		}

	}



	public function admin($data,$query){

		$data['mastheadImage'] = 'masthead.jpg';
		$data['page'] = $this->page;
		$data['action'] = $this->action;
		$data['totalRecords'] = 0;
			
		if($query != null){
			$data['totalRecords'] = $query->num_rows();
			$data['query'] = $query;
		}
			
		$this->loadAdminPage($this->page,$data);
	}


	public function createLog($table , $action ,  $message){

		$updatedby = $this->session->userdata('user_id');

		$this->db->query("INSERT INTO  logs (id ,action ,affected_table , description ,createdby, createdon,  valid ) VALUES (NULL ,  '$action',  '$table',  '$message' ,$updatedby ,NOW(), 1)");

	}

	public function clientUpdateLog($table , $action ,  $message){

		$updatedby = $this->session->userdata('client_id');

		$this->db->query("INSERT INTO  logs (id ,action ,affected_table , description ,createdby, createdon,  valid ) VALUES (NULL ,  '$action',  '$table',  '$message' ,$updatedby ,NOW(), 1)");

	}


	/**************************/


	public function validateFields(){
		$this->form_validation->set_error_delimiters('<label>', '</label><br>');
		return $this->form_validation->run();



	}


	public function transactionListByUser($clientid , $startDate , $endDate){
		//$query = 'SELECT CONCAT( client.firstname," ", client.lastname ) AS clientname,trans.id as trans_id, referencenumber, clientid , commodity, volume, _4wheeler,dr_number,';
		//$query .= ' _6wheeler, _10wheeler, _10container, _20container, _40container, pickupaddress, dateofpickup, deliverypoint, onboarddate, intransitlocation FROM';
		//$query .= ' users AS client, transaction AS trans where client.id = trans.clientid';

		$query = "
SELECT CONCAT( client.firstname,' ', client.lastname ) AS clientname,client.id as clientid, trans.id as trans_id, referencenumber ,clientid ,  notes ,commodity, volume_qty, volume_containersize , truck_qty , truck_name , truck_company, truck_number, truck_type,
pickupaddress,dateofpickup,deliverypoint, onboarddate, intransitlocation, timeofpickup, onboardtime,dr_number , status, datedelivered, remarks, timedelivered,onboardtime , timeofpickup from users AS client, transaction AS trans where client.id = trans.clientid";


		if($clientid != null)
		$query .= ' and client.id = '.$clientid;


		if($startDate != null && $endDate != null)
		$query .= " and createdon between '$startDate' and '$endDate'";
		else if($startDate != null)
		$query .= " and createdon > '$startDate'";
		else if($endDate != null)
		$query .= " and createdon < '$endDate'";

		//echo "$query";

		return $this->db->query($query . " and trans.valid = 1");
	}


	public function transactionListByCreatedBy($createdby , $startDate , $endDate){


		$query = "
SELECT trans.createdon as trans_createdon , CONCAT( client.firstname,' ', client.lastname ) AS clientname,client.id as clientid, trans.id as trans_id, referencenumber ,clientid ,  notes ,commodity, volume_qty, volume_containersize , truck_qty , truck_name , truck_company, truck_number, truck_type,
pickupaddress,dateofpickup,deliverypoint, onboarddate, intransitlocation, timeofpickup, onboardtime,dr_number , status, datedelivered, remarks, timedelivered,onboardtime , timeofpickup from users AS client, transaction AS trans where client.id = trans.clientid and trans.valid = 1 ";


		if($createdby != null)
		$query .= ' and trans.createdby = '.$createdby;


		if($startDate != null && $endDate != null)
		$query .= " and trans.createdon >= '$startDate' and trans.createdon <='$endDate'";
		else if($startDate != null)
		$query .= " and trans.createdon >= '$startDate'";
		else if($endDate != null)
		$query .= " and trans.createdon <= '$endDate'";

		//echo "---------------$query";

		return $this->db->query($query);
	}




	public function logoutCurrentUser(){
		$this->session->unset_userdata('client_id');
		$this->session->unset_userdata('client_fullname');
		$this->session->unset_userdata('client_email');
		$this->session->unset_userdata('client_type');
		$this->session->unset_userdata('client_referencenumber');

	}



	public function getTransaction($transid){
		//$query = 'SELECT CONCAT( client.firstname," ", client.lastname ) AS clientname,client.id as clientid, trans.id as trans_id, referencenumber, clientid , notes,commodity, volume, _4wheeler,';
		//$query .= ' _6wheeler, _10wheeler, _10container, _20container, _40container, pickupaddress, dateofpickup, deliverypoint, onboarddate, intransitlocation, dr_number,status,datedelivered,remarks,timedelivered,onboardtime,timeofpickup   FROM';



		$query = "SELECT CONCAT( client.firstname,' ', client.lastname ) AS clientname,client.id as clientid, trans.id as trans_id, referencenumber ,clientid ,  notes ,commodity, volume_qty, volume_containersize , volume_packages , volume_volume, truck_qty , truck_name , truck_company, truck_number, truck_type,
pickupaddress,dateofpickup,deliverypoint, onboarddate, intransitlocation, timeofpickup, onboardtime,dr_number , status, datedelivered, remarks, timedelivered,onboardtime , timeofpickup from ";


		$query .= ' users AS client, transaction AS trans where client.id = trans.clientid and trans.id = '.$transid.' and trans.valid = 1 limit 1';
		return $this->db->query($query);
	}





	public function creationFields(){
		return ",createdby,createdon,valid,updatedby,updatedon";

	}

	public function creationValues(){

		$createdby = $this->session->userdata('user_id');
		return  ",$createdby, NOW() ,true,$createdby,NOW()";

	}


	public function updateFieldsAndValues(){
		//	$updatedon = CURDATE();
		$updatedby = $this->session->userdata('user_id');
		return ",updatedby='$updatedby' ,updatedon =  'CURDATE()";

	}

	public function updateFields(){
		return ",updatedby,updatedon";

	}


	public function updateValues(){
		//$updatedon = CURDATE();
		$updatedby = $this->session->userdata('user_id');
		return ",CURDATE(),$updatedon";
	}


	public function generatePaginationLinks($config){
		$config['num_links'] = 1;
		$config['use_page_numbers'] = TRUE;



		$config['first_link'] = 'First';


		$config['last_link'] = 'Last';

		$config['cur_tag_open'] = '<a  style="border-color: #8C3521;border-color: #8C3521;color: white;">';
		$config['cur_tag_close'] = '</a>';
		$config['next_link'] = '&gt;';

		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		return $this->pagination->create_links();

	}


	
	
	public function sendEmail($emailMessageTemplate,  $details , $subject){
			
		$this->load->library('email');
	    $this->load->library('parser');
	    $this->email->clear();
	    $config['mailtype'] = "html";
	   // $config['protocol']='smtp';
	    $config['protocol'] = 'sendmail'; 
	    $config['mailpath'] = '/usr/sbin/sendmail'; 
		 $config['smtp_host']='ssl://smtp.googlemail.com';
		 $config['smtp_port']='465';
		 $config['smtp_timeout']='30';
		 $config['smtp_user']='skybestinternational@gmail.com';
		 $config['smtp_pass']='narutooo';
		 $config['charset']='utf-8';
		 $config['newline']="\r\n";
	    $this->email->initialize($config);
	    $this->email->set_newline("\r\n");
	    $this->email->from('skybestinternational@gmail.com', 'Skybest Corp');
	   // $list = array('anthonyteoxon@gmail.com', 'anthonyteoxon@yahoo.com');
	   // $details['receipients'] = array('anthonyteoxon@gmail.com', 'anthonyteoxon@yahoo.com');
	    $this->email->to($details['receipients']);
	    $data = $details;
	    
	    /*
	    $details['receipients'] = array('anthonyteoxon@gmail.com', 'anthonyteoxon@yahoo.com');
	    $details['subject'] = "Contact Us";
	    
	    */
		$htmlMessage =  $this->parser->parse("emailtemplates/$emailMessageTemplate", $data );
		
	   // $htmlMessage = "SAMPLE EMAIL MESSAGE";//$this->parser->parse('messages/email', $data, true);
	    $this->email->subject( $subject);
	    $this->email->message($htmlMessage);
	    
	    
	    if ($this->email->send()) {
	       // echo 'Your email was sent, thanks chamil.';
	    } else {
	        show_error($this->email->print_debugger());
	    }
		
	}



}
// END Controller class

/* End of file Controller.php */
/* Location: ./system/core/Controller.php */